package com.xinruke.hostels.support.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinruke.hostels.central.manage.interfaces.dto.BuildingDetailQueryResultDTO;
import com.xinruke.hostels.common.cache.util.SysSqlParamUtil;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.exception.ArgumentException;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.XtZidianGroup;
import com.xinruke.hostels.common.po.XtZidiancanshu;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.support.interfaces.dto.*;
import com.xinruke.hostels.support.mapper.XtZidianGroupMapper;
import com.xinruke.hostels.support.mapper.XtZidiancanshuMapper;
import com.xinruke.hostels.support.service.SystemDictService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SystemDictServiceImpl
 * @CreateDate 2019/6/17
 * @Author FengXinQiang
 * @Version V1.0.0.0
 * @Decription 系统字典Service实现
 */
@Service
public class SystemDictServiceImpl implements SystemDictService {
    @Resource
    XtZidiancanshuMapper zidiancanshuMapper;

    @Resource
    XtZidianGroupMapper xtZidianGroupMapper;

    @Override
    public List<XtZidiancanshu> getSystemDictList(SystemDictQueryDTO systemDictQueryDTO) {
        systemDictQueryDTO.setPageNo(1);
        systemDictQueryDTO.setPageSize(10000);
        MyExample example = new MyExample(XtZidiancanshu.class, systemDictQueryDTO.getQueryConditions(), systemDictQueryDTO.getOrderFields());

        List<XtZidiancanshu> list = zidiancanshuMapper.selectByExample(example);
        return list;
    }

    @Override
    public ResultVO<RowsDataVO<SystemDictGroupQueryResultDTO>> getSystemDictGroupList(SystemDictGroupQueryDTO groupQueryDTO) {
        ResultVO<RowsDataVO<SystemDictGroupQueryResultDTO>> resultVO = ResultVO.fail();

        RowsDataVO<SystemDictGroupQueryResultDTO> rowsDataVO = new RowsDataVO<>();

        QueryConditions conditions = groupQueryDTO.getQueryConditions();
        //拼装查询条件
        conditions.addCondition("fenzubianma", EConditionOperator.LIKE, groupQueryDTO.getFenzubianma());
        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, XtZidiancanshu.SHANCHUBIAOSHI_BUSHANCHU);

        //拼装排序字段
        MyExample example = new MyExample(XtZidianGroup.class, conditions, groupQueryDTO.getOrderFields());
        Page<BuildingDetailQueryResultDTO> page = PageHelper.startPage(groupQueryDTO.getPageNo(), groupQueryDTO.getPageSize());
        List<XtZidianGroup> xtZidianGroups = xtZidianGroupMapper.selectByExample(example);
        //获取字典集合
        List<SystemDictGroupQueryResultDTO> resultList = xtZidianGroups.stream().map(g -> {
            SystemDictGroupQueryResultDTO resultDTO = new SystemDictGroupQueryResultDTO();
            BeanUtils.copyProperties(g, resultDTO);
            return resultDTO;
        }).collect(Collectors.toList());

        rowsDataVO.setPageNo(page.getPageNum());
        rowsDataVO.setTotalRecords(page.getTotal());
        rowsDataVO.setTotalPages(page.getPages());
        rowsDataVO.setRows(resultList);

        resultVO = ResultVO.success();
        resultVO.setData(rowsDataVO);

        return resultVO;

    }

    @Override
    @Transactional
    public ResultVO addParam(SystemDictAddQueryDTO systemDictAddQueryDTO) {

        ResultVO resultVO = checkIsCanAdd(systemDictAddQueryDTO);
        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        //校验是否需要添加字典分组
        List<XtZidianGroup> xtZidianGroupList = xtZidianGroupMapper.selectByExample(Example.builder(XtZidianGroup.class)
                .where(Sqls.custom()
                        .andEqualTo("fenzubianma", systemDictAddQueryDTO.getFenzubianma())
                        .andEqualTo("shanchubiaoshi", XtZidianGroup.SHANCHUBIAOSHI_WU_XIOA)
                ).build()
        );
        //如果不存在该字典分组，新增
        if (CollectionUtils.isEmpty(xtZidianGroupList)) {
            XtZidianGroup xtZidianGroup = new XtZidianGroup();
            xtZidianGroup.setFenzubianma(systemDictAddQueryDTO.getFenzubianma());
            xtZidianGroup.setFenzumingcheng(systemDictAddQueryDTO.getMiaoshu());
            xtZidianGroup.setShanchubiaoshi(XtZidianGroup.SHANCHUBIAOSHI_WU_XIOA);
            int i = xtZidianGroupMapper.insertSelective(xtZidianGroup);
            if (i < 1) {
                throw new ArgumentException("插入分组失败");
            }
        }


        XtZidiancanshu xtZidiancanshu = new XtZidiancanshu();
        BeanUtils.copyProperties(systemDictAddQueryDTO, xtZidiancanshu);
        xtZidiancanshu.setShanchubiaoshi(XtZidiancanshu.SHANCHUBIAOSHI_BUSHANCHU);
        xtZidiancanshu.setChuangjianshijian(new Date());
        int insert = zidiancanshuMapper.insert(xtZidiancanshu);
        if (insert < 1) {
            throw new ArgumentException("插入字典失败");

        }
        return resultVO;

    }

    private ResultVO checkIsCanAdd(SystemDictAddQueryDTO systemDictAddQueryDTO) {
        ResultVO resultVO = ResultVO.success();
        List<XtZidiancanshu> xtZidiancanshuList = zidiancanshuMapper.selectByExample(Example.builder(XtZidiancanshu.class).where(Sqls.custom()
                .andEqualTo("fenzubianma", systemDictAddQueryDTO.getFenzubianma())
                .andEqualTo("shanchubiaoshi", XtZidiancanshu.SHANCHUBIAOSHI_BUSHANCHU)
                .andEqualTo("canshuzhi", systemDictAddQueryDTO.getCanshuzhi())
        ).build());
        if (!CollectionUtils.isEmpty(xtZidiancanshuList)) {
            resultVO.setCode(ResultVO.FAIL);
            resultVO.setMessage("参数值已存在");
            return resultVO;
        }
        return resultVO;

    }

    @Override
    @Transactional
    public ResultVO del(SystemDictDelQueryDTO dictDelQueryDTO) {
        ResultVO resultVO = ResultVO.fail();
        XtZidiancanshu xtZidiancanshu = new XtZidiancanshu();
        BeanUtils.copyProperties(dictDelQueryDTO, xtZidiancanshu);
        xtZidiancanshu.setShanchubiaoshi(XtZidiancanshu.SHANCHUBIAOSHI_SHANCHU);
        xtZidiancanshu.setChuangjianshijian(new Date());
        int del = zidiancanshuMapper.updateByPrimaryKeySelective(xtZidiancanshu);
        if (del < 1) {
            return resultVO;
        }
        resultVO.setCode(ResultVO.SUCCESS);
        resultVO.setMessage("success");

        return resultVO;
    }

    @Override
    @Transactional
    public ResultVO modifyParam(SystemDictModifyQueryDTO modifyQueryDTO) {

        XtZidiancanshu xtZidiancanshu = new XtZidiancanshu();
        BeanUtils.copyProperties(modifyQueryDTO, xtZidiancanshu);
        int insert = zidiancanshuMapper.updateByPrimaryKeySelective(xtZidiancanshu);
        if (insert < 1) {
            throw new ArgumentException("更新失败");
        }

        return ResultVO.success();
    }

    @Override
    public ResultVO<List<SystemDictAllQueryResultDTO>> getAllDict(SystemDictAllQueryDTO systemDictAllQueryDTO) {

        ResultVO<List<SystemDictAllQueryResultDTO>> resultVO = ResultVO.fail();
        //查询所有分组信息
        List<XtZidianGroup> xtZidianGroupList = xtZidianGroupMapper.selectByExample(Example.builder(XtZidianGroup.class)
                .where(Sqls.custom()
                        .andEqualTo("shanchubiaoshi", XtZidianGroup.SHANCHUBIAOSHI_WU_XIOA)
                ).build());
        //查询所有字典参数信息
        List<XtZidiancanshu> xtZidiancanshuList = zidiancanshuMapper.selectByExample(Example.builder(XtZidiancanshu.class)
                .where(Sqls.custom()
                        .andEqualTo("shanchubiaoshi", XtZidiancanshu.SHANCHUBIAOSHI_BUSHANCHU)
                ).build());

        //最终结果
        List<SystemDictAllQueryResultDTO> data = xtZidianGroupList.stream().map(g -> {
            SystemDictAllQueryResultDTO resultDTO = new SystemDictAllQueryResultDTO();
            BeanUtils.copyProperties(g, resultDTO);
            //得到下级
            resultDTO.setSubParamList(getSubParamList(xtZidiancanshuList, g.getFenzubianma()));
            return resultDTO;
        }).collect(Collectors.toList());

        JSONArray sysParams = SysSqlParamUtil.getSysParams(SysDicConstant.JIUDIAN_MINGCHENG.toUpperCase());

        SystemDictAllQueryResultDTO resultDTO = new SystemDictAllQueryResultDTO();
        resultDTO.setFenzumingcheng("酒店名称");
        resultDTO.setFenzubianma(SysDicConstant.JIUDIAN_MINGCHENG);
        List<SystemDictQueryResultDTO> list = new ArrayList<>();
        sysParams.toJavaList(JSONObject.class).forEach(e -> {
            SystemDictQueryResultDTO systemDictQueryResultDTO = new SystemDictQueryResultDTO();
            String canshuzhi = e.getString("key");
            String canshumingcheng = e.getString("value");

            systemDictQueryResultDTO.setCanshuzhi(canshuzhi);
            systemDictQueryResultDTO.setCanshumingcheng(canshumingcheng);
            list.add(systemDictQueryResultDTO);
        });
        resultDTO.setSubParamList(list);
        data.add(resultDTO);


        sysParams = SysSqlParamUtil.getSysParams(SysDicConstant.JIUDIAN_DISHI.toUpperCase());

        SystemDictAllQueryResultDTO resultDTO1 = new SystemDictAllQueryResultDTO();
        resultDTO1.setFenzumingcheng("酒店地市");
        resultDTO1.setFenzubianma(SysDicConstant.JIUDIAN_DISHI);
        List<SystemDictQueryResultDTO> list1 = new ArrayList<>();
        sysParams.toJavaList(JSONObject.class).forEach(e -> {
            SystemDictQueryResultDTO systemDictQueryResultDTO = new SystemDictQueryResultDTO();
            String canshuzhi = e.getString("key");
            String canshumingcheng = e.getString("value");

            systemDictQueryResultDTO.setCanshuzhi(canshuzhi);
            systemDictQueryResultDTO.setCanshumingcheng(canshumingcheng);
            list1.add(systemDictQueryResultDTO);
        });
        resultDTO1.setSubParamList(list1);
        data.add(resultDTO1);

        resultVO.setCode(ResultVO.SUCCESS);
        resultVO.setMessage("success");
        resultVO.setData(data);
        return resultVO;
    }

    /**
     * 得到下级字典
     *
     * @param xtZidiancanshuList
     * @param fenzubianma
     * @return
     */
    private List<SystemDictQueryResultDTO> getSubParamList(List<XtZidiancanshu> xtZidiancanshuList, String fenzubianma) {
        return xtZidiancanshuList.stream()
                .filter(p -> p.getFenzubianma().equals(fenzubianma))
                .sorted(Comparator.comparing(XtZidiancanshu::getZhanshishunxu))
                .map(p -> {
                    SystemDictQueryResultDTO queryResultDTO = new SystemDictQueryResultDTO();
                    BeanUtils.copyProperties(p, queryResultDTO);
                    return queryResultDTO;
                })
                .collect(Collectors.toList());
    }
}
